package org.dromara.crawler.mongo.mongoservice.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.util.ObjectUtil;
import com.mongoplus.conditions.query.LambdaQueryChainWrapper;
import com.mongoplus.model.PageResult;
import com.mongoplus.service.impl.ServiceImpl;
import org.bson.Document;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.crawler.domain.bo.KnowledgeTargetBo;
import org.dromara.crawler.mongo.mongodomain.KnowledgeTarget;
import org.dromara.crawler.mongo.mongoservice.KnowledgeTargetService;
import org.springframework.stereotype.Service;
import org.dromara.common.core.utils.DateUtils;

import java.util.*;


@Service
public class KnowledgeTargetServiceImpl extends ServiceImpl<KnowledgeTarget> implements KnowledgeTargetService {


//    @Autowired
//    private KnowledgeTargetService knowledgeBaseService;

    @Override
    public List<KnowledgeTarget> getAll() {
        // 查询所有知识库数据
        return this.list();
    }

    @Override
    public KnowledgeTarget queryById(String id) {
        // 根据 ID 查询单条知识库数据
        return this.getById(id);
    }


   @Override
    public List<KnowledgeTarget> queryByCondition(KnowledgeTargetBo knowledgeTargetBo) {
        // 构建查询条件
        LambdaQueryChainWrapper<KnowledgeTarget> wrapper = this.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotEmpty(knowledgeTargetBo.getEventFirstLevel()), KnowledgeTarget::getEventFirstLevel, knowledgeTargetBo.getEventFirstLevel());
        wrapper.eq(ObjectUtil.isNotEmpty(knowledgeTargetBo.getEventSecondLevel()), KnowledgeTarget::getEventSecondLevel, knowledgeTargetBo.getEventSecondLevel());
        wrapper.eq(ObjectUtil.isNotEmpty(knowledgeTargetBo.getSourceTitle()), KnowledgeTarget::getSourceTitle, knowledgeTargetBo.getSourceTitle());
        wrapper.eq(ObjectUtil.isNotEmpty(knowledgeTargetBo.getName()), KnowledgeTarget::getName, knowledgeTargetBo.getName());
        wrapper.eq(ObjectUtil.isNotEmpty(knowledgeTargetBo.getTargetId()), KnowledgeTarget::getTargetId, knowledgeTargetBo.getTargetId());

        // 执行查询
        return wrapper.list();
    }

    public Page<KnowledgeTarget> queryByPage(KnowledgeTargetBo knowledgeTargetBo, PageQuery pageQuery) {
        if (pageQuery == null) {
            pageQuery = new PageQuery();
        }
        if (pageQuery.getPageNum() == null || pageQuery.getPageNum() <= 0) {
            pageQuery.setPageNum(1); // 默认第一页
        }
        if (pageQuery.getPageSize() == null || pageQuery.getPageSize() <= 0) {
            pageQuery.setPageSize(10); // 默认每页10条
        }

        LambdaQueryChainWrapper<KnowledgeTarget> wrapper = this.lambdaQuery();
        wrapper.like(ObjectUtil.isNotEmpty(knowledgeTargetBo.getEventFirstLevel()), KnowledgeTarget::getEventFirstLevel, knowledgeTargetBo.getEventFirstLevel());
        wrapper.like(ObjectUtil.isNotEmpty(knowledgeTargetBo.getEventSecondLevel()), KnowledgeTarget::getEventSecondLevel, knowledgeTargetBo.getEventSecondLevel());
        wrapper.like(ObjectUtil.isNotEmpty(knowledgeTargetBo.getSourceTitle()), KnowledgeTarget::getSourceTitle, knowledgeTargetBo.getSourceTitle());
        wrapper.like(ObjectUtil.isNotEmpty(knowledgeTargetBo.getName()), KnowledgeTarget::getName, knowledgeTargetBo.getName());
        wrapper.like(ObjectUtil.isNotEmpty(knowledgeTargetBo.getType()), KnowledgeTarget::getType, knowledgeTargetBo.getType());

        PageResult<KnowledgeTarget> pageResult = this.page(wrapper, pageQuery.getPageNum(), pageQuery.getPageSize());
        List<KnowledgeTarget> records = pageResult.getContentData();
        records.stream().forEach(knowledgeTarget -> {
            Document document = knowledgeTarget.getData();
            // 处理data中的time字段，如果存在则转换为Date类型
            if(ObjectUtil.isNotEmpty(document.get("time"))){
                Object timeObj = document.get("time");
                if (timeObj instanceof String) {
                    Date date = DateUtils.parseDate(timeObj.toString());
                    // 更新data中的time字段为Date类型
                    document.put("time", date);
                }
            }
        });

        Page<KnowledgeTarget> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        page.setRecords(records);
        page.setTotal(pageResult.getTotalSize());
        return page;
    }


    @Override
    public boolean add(KnowledgeTarget knowledgeTarget) {
        setTypeByEventLevels(knowledgeTarget);

        // 处理data中的time字段，如果存在则转换为Date类型
        if (knowledgeTarget.getData() != null && knowledgeTarget.getData().containsKey("time")) {
            Object timeObj = knowledgeTarget.getData().get("time");
            if (timeObj instanceof String) {
                Date date = DateUtils.parseDate(timeObj.toString());
                // 更新data中的time字段为Date类型
                knowledgeTarget.getData().put("time", date);
            }
        }

        // 保持name、data中的name和sourceTitle同步
        if (knowledgeTarget.getName() != null) {
            // 如果顶层name存在，同步到data中的name和sourceTitle
            if (knowledgeTarget.getData() == null) {
                knowledgeTarget.setData(new Document());
            }
            knowledgeTarget.getData().put("name", knowledgeTarget.getName());
            knowledgeTarget.setSourceTitle(knowledgeTarget.getName());
        } else if (knowledgeTarget.getData() != null && knowledgeTarget.getData().containsKey("name")) {
            // 如果data中的name存在，同步到顶层name和sourceTitle
            Object nameObj = knowledgeTarget.getData().get("name");
            if (nameObj != null) {
                knowledgeTarget.setName(nameObj.toString());
                knowledgeTarget.setSourceTitle(nameObj.toString());
            }
        }

        String targetId = generateTargetId(knowledgeTarget.getEventFirstLevel(), knowledgeTarget.getEventSecondLevel());
        if (knowledgeTarget.getData() == null) {
            knowledgeTarget.setData(new Document());
        }
        knowledgeTarget.getData().put("target_id", targetId);
        knowledgeTarget.setTargetId(targetId);
        return this.save(knowledgeTarget);
    }

    @Override
    public boolean updateByTargetId(KnowledgeTarget knowledgeTarget) {
        LambdaQueryChainWrapper<KnowledgeTarget> wrapper = this.lambdaQuery();
        String targetId = null;
        if (knowledgeTarget.getData() != null && knowledgeTarget.getData().containsKey("target_id")) {
            targetId = knowledgeTarget.getData().getString("target_id");
        } else if (knowledgeTarget.getTargetId() != null) {
            targetId = knowledgeTarget.getTargetId();
        }
        if (targetId == null) {
            return false;
        }

        wrapper.eq("target_id", targetId);
        List<KnowledgeTarget> targets = wrapper.list();

        if (!targets.isEmpty()) {
            KnowledgeTarget existingTarget = targets.get(0);

            setTypeByEventLevels(knowledgeTarget);


            if (knowledgeTarget.getData() != null && knowledgeTarget.getData().containsKey("time")) {
                Object timeObj = knowledgeTarget.getData().get("time");
                if (timeObj instanceof String) {
                    Date date = DateUtils.parseDate(timeObj.toString());
                    // 更新data中的time字段为Date类型
                    knowledgeTarget.getData().put("time", date);
                }
            }

            // 保持name、data中的name和sourceTitle同步
            if (knowledgeTarget.getName() != null) {

                if (knowledgeTarget.getData() == null) {
                    knowledgeTarget.setData(new Document());
                }
                knowledgeTarget.getData().put("name", knowledgeTarget.getName());
                knowledgeTarget.setSourceTitle(knowledgeTarget.getName());
            } else if (knowledgeTarget.getData() != null && knowledgeTarget.getData().containsKey("name")) {

                Object nameObj = knowledgeTarget.getData().get("name");
                if (nameObj != null) {
                    knowledgeTarget.setName(nameObj.toString());
                    knowledgeTarget.setSourceTitle(nameObj.toString());
                }
            }

            knowledgeTarget.setId(existingTarget.getId());
            knowledgeTarget.setTargetId(targetId);

            if (knowledgeTarget.getData() == null) {
                knowledgeTarget.setData(new Document());
            }
            knowledgeTarget.getData().put("target_id", targetId);

            return this.updateById(knowledgeTarget);
        }
        return false;
    }


    private void setTypeByEventLevels(KnowledgeTarget knowledgeTarget) {
        String eventFirstLevel = knowledgeTarget.getEventFirstLevel();
        String eventSecondLevel = knowledgeTarget.getEventSecondLevel();


        if (("台海政治".equals(eventFirstLevel) || "台海经济".equals(eventFirstLevel) || "台海军事".equals(eventFirstLevel))) {
            if ("人物目标".equals(eventSecondLevel)) {
                knowledgeTarget.setType("人物");
            } else if ("组织目标".equals(eventSecondLevel)) {
                if ("台海政治".equals(eventFirstLevel) || "台海经济".equals(eventFirstLevel)) {
                    knowledgeTarget.setType("政治组织");
                } else if ("台海军事".equals(eventFirstLevel)) {
                    knowledgeTarget.setType("军事组织");
                }
            } else if ("机场目标".equals(eventSecondLevel)) {
                knowledgeTarget.setType("机场");
            } else if ("港口目标".equals(eventSecondLevel)) {
                knowledgeTarget.setType("港口");
            } else if ("军舰目标".equals(eventSecondLevel)) {
                knowledgeTarget.setType("军舰");
            }
        }
    }

    private String generateTargetId(String eventFirstLevel, String eventSecondLevel) {
        String prefix = "TARGET";
        if ("人物目标".equals(eventSecondLevel)) {
            prefix = "PER";
        } else if ("组织目标".equals(eventSecondLevel)) {
            if ("台海政治".equals(eventFirstLevel) || "台海经济".equals(eventFirstLevel)) {
                prefix = "ORG";
            } else if ("台海军事".equals(eventFirstLevel)) {
                prefix = "ORG";
            }
        } else if ("机场目标".equals(eventSecondLevel)) {
            prefix = "AIR";
        } else if ("港口目标".equals(eventSecondLevel)) {
            prefix = "PORT";
        } else if ("军舰目标".equals(eventSecondLevel)) {
            prefix = "WAR";
        }


        return prefix + "-" + UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    }

    @Override
    public boolean deleteByTargetId(String targetId) {
        // 根据 target_id 删除知识目标
        LambdaQueryChainWrapper<KnowledgeTarget> wrapper = this.lambdaQuery();
        // 从顶层target_id字段中查找
        wrapper.eq("target_id", targetId);
        List<KnowledgeTarget> targets = wrapper.list();
        if (!targets.isEmpty()) {
            return this.removeById(targets.get(0).getId());
        }
        return false;
    }

    @Override
    public Map<String, Long> getTargetEventFirstLevelStats() {
        Map<String, Long> stats = new HashMap<>();
        List<String> categories = Arrays.asList("台海政治", "台海经济", "台海军事");
        for(String category : categories) {
            long count = this.lambdaQuery()
                .eq(KnowledgeTarget::getEventFirstLevel, category)
                .count();
            stats.put(category, count);
        }
        return stats;
    }





}
